#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <functional>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
using namespace std;
template <class T, class V>
using task = function<void(T, V)>;

// 模拟封装C++线程库
template <class T, class V>
class thread
{
public:
    // 构造函数
    thread(const V &name, task<T, V> func, T lock)
        : _tid(0), _threadname(name), _func(func), _isrunning(false), _lock(lock)
    {
    }

    static void *Threadfunc(void *args)
    {
        thread *This = static_cast<thread *>(args);
        This->_func(This->_lock, This->_threadname);
        return nullptr;
    }

    // 启动线程
    void Start()
    {
        if (_isrunning)
        {
            return;
        }
        // 创建线程
        int n = pthread_create(&_tid, nullptr, Threadfunc, (void *)this);
        if (0 == n)
        {
            _isrunning = true;
        }
        return;
    }
    void Join()
    {
        if (!_isrunning)
        {
            return;
        }
        pthread_join(_tid, nullptr);
        _isrunning = false;
    }

    // 析构函数
    ~thread()
    {
    }

private:
    pthread_t _tid;
    string _threadname;
    task<T, V> _func;
    bool _isrunning;
    T _lock;
};
